import * as THREE from "three"
import RenderLayers, { RenderLayer } from "../utils/RenderLayers"
import RoomMesh from "../mesh/RoomMesh"
import OrderedMap from "../utils/OrderedMap"
export default class FloorMesh extends THREE.Object3D {
  renderLayer: RenderLayer
  roomMeshes: any
  boundingBox: any
  size: any
  center: any
  _chunks: any[]
  built: boolean
  meshGroup: any
  floorId: any
  constructor(e, t = RenderLayers.ALL) {
    super()
    this.renderLayer = t
    this.roomMeshes = new OrderedMap(e => e.meshSubgroup)
    this.boundingBox = new THREE.Box3()
    this.size = new THREE.Vector3()
    this.center = new THREE.Vector3()
    this._chunks = []
    this.built = !1
    this.name = `FloorMesh:${e}`
    this.meshGroup = e
    this.floorId = void 0
  }
  dispose() {
    this.reset(), this.roomMeshes.clear()
  }
  reset() {
    for (const e of this.roomMeshes) e.dispose(), this.remove(e)
    ;(this._chunks.length = 0), (this.built = !1)
  }
  addChunk(e) {
    const t = this.getOrCreateRoomMesh(e.meshSubgroup)
    this._chunks.push(e), t.addChunk(e)
  }
  build() {
    if (this.built) throw new Error("build() should only be called once")
    this.boundingBox.makeEmpty()
    for (const e of this.roomMeshes) this.add(e), this.boundingBox.union(e.boundingBox)
    ;(this.center = this.boundingBox.getCenter(this.center)), (this.size = this.boundingBox.getSize(this.size)), (this.built = !0)
  }
  get chunks() {
    return this._chunks
  }
  getOrCreateRoomMesh(e) {
    let t = this.roomMeshes.get(e)
    return t || ((t = new RoomMesh(this.meshGroup, e, this.renderLayer)), this.roomMeshes.add(t), this.add(t)), t
  }
}
